package sum.book.auth.server.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import sum.book.auth.server.service.impl.CustomUserDetailServiceImpl;
import sum.book.auth.server.service.impl.RedisAuthorizationCodeServicesImpl;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Auther: ZhangGN
 * @Description: 认证服务器搭建
 * @Date 2022/11/18 15:50
 **/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    DataSource dataSource;

    @Resource
    CustomUserDetailServiceImpl userDetailService;

    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    RedisAuthorizationCodeServicesImpl redisAuthorizationCodeServicesImpl;

    @Resource
    @Qualifier(value = "customClientDetailsService")
    ClientDetailsService customClientDetailsService;


    @Resource
    @Qualifier(value = "customAuthorizationServerTokenServices")
    AuthorizationServerTokenServices customAuthorizationServerTokenServices;


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .authorizationCodeServices(redisAuthorizationCodeServicesImpl)
                .userDetailsService(userDetailService)
                .tokenServices(customAuthorizationServerTokenServices);
    }



    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource).clients(customClientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()") //开放获取token(这个是做JWT的时候开放的！也就是资源服可以通过这个请求得到JWT加密的key，目前这里没什么用，可以不用配置)
                .checkTokenAccess("permitAll()") //开放远程token检查   /oauth/check_token  body  token
                .allowFormAuthenticationForClients();
    }
}
